<template>
  <view class="index">
    <!-- 你的标记点数据 -->
    <!-- {{latitude}}
    {{longitude}}
    {{latitude2}}
    {{longitude2}} -->
    <!-- 下拉框 -->
    <div class="top_tip2">
      <picker mode="selector" :range="districts" @change="onDistrictChange"
        :value="districts.findIndex(item => item == selectedDistrict)" class="selectOne picker_box">
        <div class="picker">
          <div class="left1">镇/街道：</div>
          <span class="right">
            <span class="txt">
              {{ selectedDistrict || "请选择" }}
            </span>
            <img :src="rightImg" alt="" width="10px" height="10px" />
          </span>
        </div>
      </picker>
      <picker mode="selector" :range="towns" :disabled="towns.length === 0"
        :value="towns.findIndex(item => item == selectedTown)" @change="onTownChange" class="picker_box selectTwo">
        <div class="picker" @click="onClickTown">
          <div class="left2">村/社区：</div>
          <span class="right">
            <span class="txt">
              {{ selectedTown || "请选择" }}
            </span>
            <img :src="rightImg" alt="" width="10px" height="10px" />
          </span>
        </div>
      </picker>
      <div class="ok" @click="okStep">
        <div class="btn">
          确定
        </div>
      </div>
    </div>
    <!-- 区域信息 -->
    <div class="tree_info" v-show="selectedRecordArea.area">
      <div class="title">助绿信息</div>
      <div class="tree_card">
        <div class="row">
          <div class="span">助绿区域</div>
          <span class="val">
            {{ selectedRecordArea.area }}
          </span>
        </div>
        <div class="row">
          <div class="span">助绿总棵树</div>
          <span class="val">
            {{ selectedRecordArea.goods_count }}棵
          </span>
        </div>
        <div class="row" v-show="selectedRecordArea.amount_count > 0">
          <div class="span">助绿金次数</div>
          <span class="val">
            {{ selectedRecordArea.amount_count }}次
          </span>
        </div>
        <div class="row" v-show="selectedRecordArea.goods.length > 0">
          <div class="span">助绿树种:</div>
          <div class="val2" >
            <div class="item" v-for="(item, index) in selectedRecordArea.goods" >
              {{ item.planting_tree_name }}{{ item.count }}棵
            </div>
            <!-- <div class="item">
              人面子99999棵 樟树9999棵 莞香999棵 木棉99棵 紫荆9棵 凤凰木9999棵 紫薇99999棵 苹果树999棵 桃花99棵 梨树9棵
            </div> -->
          </div>
        </div>
        <!-- <div class="row">
              <div class="span">规格</div>
              <span class="val">
                {{ payObj.planting_tree_specification_name }}
              </span>
            </div> -->
      </div>
    </div>
    <map id="map" v-show="scale < swatchMapScale" style="width: 100%; height: 100vh" :latitude="latitude" :longitude="longitude"
      :optimize="true" :scale="scale" :markers="markers" :show-location="true" @markertap="MarkerTap"
      @regionChange="handleRegionChange" />
    <map id="map2IsShow" v-if="map2IsShow" v-show="scale >= swatchMapScale" style="width: 100%; height: 100vh" :longitude="longitude"
      :latitude="latitude" :optimize="true" :scale="scale" :markers="markers2" :show-location="true"
      @markertap="MarkerTap" @regionChange="handleRegionChange2" />

    <!-- 弹出层 -->
    <nut-popup v-model:visible="showPopup" position="bottom" closeable :style="{ height: '80%' }">
      <view class="nut_popup_box">
        <div class="top_title">你想要种什么品种的树请选择</div>
        <div class="tree_box">
          <div class="top">
            <div class="left_box">
              <!-- <view class="img"></view> -->
              <img :src="treeObj.currentSelect.picture_path" class="img" alt="" />
            </div>
            <div class="right_box">
              <div class="title">{{ treeObj.currentSelect.planting_area_name }} <span class="small_tree"> (已助绿{{ selectedRecordArea.goods_count}}棵)</span>
              </div>
              <div class="mid_title">{{ treeObj.sub_title }}</div>
              <div class="mid_title2">{{ treeObj.memo }}</div>
              <div class="small_title">已选: {{ treeObj.treeSpecTitle }}</div>
              <div class="small_title">价格:
                <i v-show="treeObj.step == 1">{{ treeObj.planting_tree_specification_amount_min ===
                  treeObj.planting_tree_specification_amount_max ? treeObj.planting_tree_specification_amount_min :
                  treeObj.planting_tree_specification_amount_min + ' ~ ' +
                  treeObj.planting_tree_specification_amount_max }}</i>
                <i v-show="treeObj.step == 2">{{ treeObj.donate_amount }}</i>
              </div>

              <!-- <div class="small_title">价格: {{ treeObj.planting_tree_specification_amount_max }}</div> -->
            </div>
          </div>
          <div class="select">
            <div v-show="treeObj.step == 1">
              <div class="type">种类</div>
              <div class="treeList">
                <div :class="['txt_box', index % 3 == 2 ? '' : 'margin_right']"
                  v-for="(item, index) in treeObj.treeList" :key="index" @click="changeTreeIndex(item, index)">
                  <div :class="['box', treeObj.treeIndex == index ? 'active' : '']">
                    {{ item.name }}
                    <span class="small_tree" v-if="item.type==0">已助绿{{ item.statistic_donate_record_goods_count }}棵</span>
                    <span class="small_tree" v-if="item.type==1">已助绿{{ item.statistic_donate_record_amount_count }}次</span>
                  </div>
                </div>
              </div>
              <div class="tree_button">
                <button @click="changeStep">下一步</button>
              </div>
            </div>
            <div v-show="treeObj.step == 2">
              <div class="number">
                <div class="step2Number">数量</div>
                <div class="btn_box">
                  <nut-input-number v-model="treeObj.currentSelect.number" :button-size="30" :input-width="50"
                    @add="treeObj.currentSelect.number++" @reduce="treeObj.currentSelect.number--" />
                </div>
              </div>
              <div class="type">规格</div>
              <div class="spec">
                <div :class="['txt_box']" v-for="(item, index) in treeObj.specArr" :key="index"
                  @click="changeSpecIndex(index)">
                  <div :class="[
                    'box',
                    treeObj.currentSelect.specIndex == index ? 'active' : '',
                  ]">
                    <span class="name">
                      {{ item.name }}
                    </span>
                    <!-- v-show="!item.name.includes('元')" -->
                    <span class="money" >
                      {{ item.donate_amount }}元
                    </span>
                  </div>
                </div>
              </div>
              <div class="tree_button_step2">
                <div class="Back" @click="treeObj.step = 1">上一步</div>
                <button @click="confirmStep2">
                  <span v-if="
                    Number(
                      treeObj.specArr[treeObj.currentSelect.specIndex]
                        ?.donate_amount
                    ) > 0
                  ">
                    确认助绿({{
                      (Number(
                        treeObj.specArr[treeObj.currentSelect.specIndex]
                          ?.donate_amount
                      ) * treeObj.currentSelect.number).toFixed(2)
                    }})
                  </span>
                  <span v-else>暂无可选</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </view>
    </nut-popup>
  </view>
</template>

<script>
import { reactive, computed } from "vue";
import { ref, onMounted } from "vue";
import { Map } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import right from "../../assets/img/right.png";
import icon_dot from "../../assets/img/icon_dot.png"; // tree

import {
  ApiPlanting,
  ApiListTree,
  ApiListTreeSpecification,
  ApiGetOpenId,
  ApiSelectListAreaDistrict,
  ApiStatisticDonateRecordArea,
  ApiStatisticDonateRecordAreaDistrict 
} from "../../utils/api";
// info
import { useInfoStore } from '../../store/info'
export default {
  name: "Home",
  components: {
    Map,
  },
  setup() {
    // 页面加载时间
    const mountedNum = ref(0)
    const mountedTimer = ref()
    useDidShow(() => {
      setInterval(() => {
        mountedNum.value = mountedNum.value + 0.3
        if (mountedNum.value > 5) {
        }
      }, 300)
    })

     // openid
    const registerForm = ref({
      openid: Taro.getStorageSync("openid") || "",
      sessionKey: Taro.getStorageSync("sessionKey") || "",
    });
    const getOpenId = () => {
      Taro.login({
        success(res) {
          if (res.code) {
            ApiGetOpenId(res.code).then((res) => {
              const { data } = res.data;
              const myRegisterForm = {
                openid: data.openid,
                sessionKey: data.session_key,
              };
              registerForm.value = myRegisterForm;
              Taro.setStorageSync("openid", data.openid);
              Taro.setStorageSync("sessionKey", data.session_key);
            });
          }
        },
      });
    };

    // info
    const infoStore = useInfoStore()
    // 图片 图标
    const icon_dotImg = ref(icon_dot);
    const rightImg = ref(right); //
    // 下拉框
    const districts = ref([]);// 下拉框镇列表
    const towns = ref([]); // 下拉框村列表
    const townsLatitudeList = ref([]); // 村列表总，包括名称
    const selectedDistrict = ref(""); // 当前选择的镇名称
    const selectedTown = ref(); // 当前选择的村名称

    // 镇列表数据
    const getAreaDistrict = async () => {
      const areaDistrict = await ApiSelectListAreaDistrict();
      districts.value = areaDistrict.data;
    };
    
    const areaList = ref(); // 种植区域总列表

    // 更新镇列表
    const onDistrictChange = async (e) => {
      // 所选项
      const selectedIndex = e.detail.value;
      selectedDistrict.value = districts.value[selectedIndex];  // 所选镇
      const list = getTownsByDistrict(districts.value[selectedIndex]); // 根据所选的镇来 获取村列表
      townsLatitudeList.value = list // 村总列表 后续选择村的经纬度
      towns.value = list.map((item) => item.name); // 选中村名
      if (mountedNum.value <= markers.value.length / batchSize * time / 1000) {
        // 加载5s内不默认选中第一个村
        setTimeout(async() => {
          const p = districts.value.filter(item => item == selectedDistrict.value)[0]
          if (p) {
            const res = await ApiStatisticDonateRecordAreaDistrict(p)
            selectedRecordArea.value.area = res.data.district
            selectedRecordArea.value.goods = res.data.goods
            selectedRecordArea.value.amount = res.data.amount
            selectedRecordArea.value.amount_sum = res.data.amount_sum // amount_count
            selectedRecordArea.value.goods_count = res.data.goods_count
            selectedRecordArea.value.amount_count = res.data.amount_count
          }
        },markers.value.length / batchSize * time / 1000 - mountedNum.value)
      } else {
        // selectedTown.value = towns.value[0]; // 默认选择第一个村名
        selectedTown.value = null; // 默认选择第一个村名
        // latitude.value = list[0].latitude // 第一个村纬度
        // longitude.value = list[0].longitude // 第一个村经度
        // scale.value = 16 // 缩放倍数
        // 区域信息
        const p = districts.value.filter(item => item == selectedDistrict.value)[0]
        if (p) {
          const res = await ApiStatisticDonateRecordAreaDistrict(p)
          selectedRecordArea.value.area = res.data.district
          selectedRecordArea.value.goods = res.data.goods
          selectedRecordArea.value.amount = res.data.amount
          selectedRecordArea.value.amount_sum = res.data.amount_sum
          selectedRecordArea.value.goods_count = res.data.goods_count // amount_count
          selectedRecordArea.value.amount_count = res.data.amount_count
          // console.log(p, 'p', selectedRecordArea.value.amount_count);
        }
      }
    };
    // 根据区获取对应的镇列表
    function getTownsByDistrict(district) {
      const list = areaList.value.filter((item) => item.district == district);
      return list;
    }

    // 当选择的村发生变化时，更新 selectedTown
    const onTownChange = async (e) => {
    // 通过下拉框放大地图 渲染地图2
      if (isSelectChange.value == false) {
        isSelectChange.value = true
      }
      // 渲染地图2
      if (!map2IsShow.value) {
        loadDingFn(markers.value.length / batchSize * time + 500)
        map2IsShow.value = true
        // 获取地图中心点坐标和缩放级别
        changeMapUrl() //渲染地图2
        // loadDingFn(3000)
      }
      // 所选项
      const selectedIndex = e.detail.value; //索引
      selectedTown.value = towns.value[selectedIndex]; //村名
      const list = townsLatitudeList.value.filter((item) => item.name == selectedTown.value); // 所选镇的村列表
      // 定位
  
      scale.value = 16
      selectScale.value = 16
      // setTimeout(()=>{
      latitude.value = list[0].latitude 
      longitude.value = list[0].longitude
      // }, 500)
 

           // 请求区域信息
      const p = list.filter(item => item.name == selectedTown.value)[0]

      if (p.id) {
        // 树种 改为确定时候请求
        // const ListTreeRes = await ApiListTree(p.id);
        // treeObj.treeList = ListTreeRes.data;

        const res = await ApiStatisticDonateRecordArea(p.id)
        selectedRecordArea.value.area = selectedTown.value
        selectedRecordArea.value.goods = res.data.goods
        selectedRecordArea.value.amount = res.data.amount
        selectedRecordArea.value.amount_sum = res.data.amount_sum
        selectedRecordArea.value.goods_count = res.data.goods_count
        selectedRecordArea.value.amount_count = res.data.amount_count //amount_count
        // 二次处理数据
        // treeObj.treeList.forEach(item => {
        //     const i = res.data.goods.findIndex(p => p.planting_tree_name == item.name)
        //     if(i == -1) {
        //       // item.statistic_donate_record_amount_count = 0
        //       item.statistic_donate_record_goods_count = 0
        //     } else {
        //       console.log(p, 'ppp');
        //       item.statistic_donate_record_goods_count = res.data.goods[i].count
        //       // item.statistic_donate_record_amount_count = res.data.goods[i].amount_count
        //     }
        //     if(res.data.amount_count > 0 && item.name == '助绿金') {
        //       item.statistic_donate_record_amount_count = res.data.amount_count
        //     } else if(res.data.amount_count == 0 && item.name == '助绿金'){
        //       item.statistic_donate_record_amount_count = 0
        //     }
        // })

      }
    };
    // 选择村
    const onClickTown = () => {
      if (!selectedDistrict.value) {
        Taro.showToast({
          title: '请先选择镇',
          icon: 'none',
          duration: 2000
        })
      } else if (towns.value.length == 0) {
        Taro.showToast({
          title: '所选镇无植树点',
          icon: 'none',
          duration: 2000
        })
      } else {
      }
    }

   // 底部区域信息
    const selectedRecordArea = ref({
      goods: [
        {
          "planting_tree_name": "木棉",
          "count": 8
        },
       ], amount: [{
          "planting_tree_name": "助绿金",
          "sum": "20.00"
        }]
    }); 


    // loadDing定时器
    const timer = ref() 
    const isTimer = ref(false)
    const loadDingFn = (time = 500) => {
      clearTimeout(timer)
      isTimer.value = true
      Taro.showLoading({
        title: '加载中',
      })
      timer.value = setTimeout(function () {
        Taro.hideLoading()
        isTimer.value = false
      }, time)
    }


        // 获取数据
    const getListTree = async (planting_area_id) => {
      // console.log(planting_area_id, '----');
      const ListTreeRes = await ApiListTree(planting_area_id);
      treeObj.treeList = ListTreeRes.data;
    }
    // 地图
    const markers = ref([]); // 标记点数据，可以是多个标记点的数组
    const markers2 = ref([]); // 标记点数据，可以是多个标记点的数组
    const latitude = ref(22.981017) //纬度
    const longitude = ref(113.905424) // 经度
    const latitude2 = ref(22.981017) //纬度
    const longitude2 = ref(113.905424) // 经度
    const scale = ref(9.2) // 地图当前 缩放倍数
    const selectScale = ref(9.2) // 地图下拉 缩放倍数
    const beforeScale = ref(9.2) // 地图上一次 缩放倍数
    const map2IsShow = ref(false) // 地图2是否显示
    const isSelectChange = ref(false) // 是否通过下拉选择 显示地图2
    const swatchMapScale = ref(13.1)
    let systemInfo; // 系统信息
    const anchorX = 0; // 文本标签位置
        // 请求地图数据
    const getMap = async () => {
      try {
        // 请求地图数据接口
        getAreaDistrict(); // 请求镇
        initMap(); //loadDing
        const res = await ApiPlanting();
        areaList.value = res.data; //请求地图数据接口
        // 请求种类对应的树种
        //  二次处理数据
        try {
          systemInfo = await Taro.getSystemInfo();
          console.log(systemInfo, "systemInfo");
        } catch (error) {
          console.log(error, "error systemInfo");
        }
        const mapRes = res.data.map((item) => {
          return {
            ...item,
            latitude: Number(item.latitude) || "",
            longitude: Number(item.longitude) || "",
            width: 6,
            height: 6,
            iconPath:
              icon_dotImg, //http://tree-planting.dgsxczxcjh.org.cn/image/JwcWcuL83EQCBtv2Zhb7Lc6ED76rlN6og48W5uaX.png
          };
        });

        //  批量新增标记点
        function addBatchData() {
          const endIndex = Math.min(currentIndex + batchSize, mapRes.length); // 计算本批数据的结束索引
          const newData = mapRes.slice(currentIndex, endIndex); // 获取本批数据
          markers.value = [...markers.value, ...newData]; // 将本批数据添加到 markers 中
          currentIndex += batchSize; // 更新当前数据的索引
          if (currentIndex < mapRes.length) {
            // 如果还有剩余数据，则继续添加下一批数据
            setTimeout(addBatchData, 200); // 间隔 200ms 添加下一批标记点
          }
        }
        addBatchData()
      } catch (error) {
        console.error("获取屏幕宽度失败", error);
      }

    };
    // 渲染地图
    const initMap = async () => {
      try {
        // 首次加载地图的loadDing
        // loadDingFn(3500)
        loadDingFn(markers.value.length > 0 ? markers.value.length / batchSize * time : 3500)
      } catch (error) {
        console.error("初始化地图失败:", error);
      }
    };


    // 批量新增
    const batchSize = 80; // 每批添加的数据数量
    let currentIndex = 0; // 当前数据的索引
    let currentIndex2 = 0; // 当前数据的索引
    // 间隔渲染
    const time = 200 // 假设200ms
    // const total = 600 假设数据总数
    // const total_time = total / batchSize * time
    // 渲染地图2
    function changeMapUrl() {
      const mapRes2 = areaList.value.map((item) => {
        return {
          ...item,
          latitude: Number(item.latitude) || "",
          longitude: Number(item.longitude) || "",
          width: 28,
          height: 28,
          iconPath:
            "http://tree-planting.dgsxczxcjh.org.cn/image/JwcWcuL83EQCBtv2Zhb7Lc6ED76rlN6og48W5uaX.png", //icon_dotImg
          callout: {
            content: `${item.name}`,
            color: "#000",
            fontSize: "11px",
            borderRadius: "4.5px",
            bgColor: "#fff",
            padding: "5.5px",
            display: "ALWAYS", // BYCLICK 表示点击标记时显示
            textAlign: "center",
            // systemInfo.system.includes("iOS") ||
            anchorX: systemInfo.system.includes("Windows") ||
              systemInfo.system.includes("macOS") ? -(systemInfo.screenWidth / 2) : anchorX, // 水平居中
            anchorY: 0, // 根据需要调整这个值，使气泡出现在标记点的正上方
          },
        };
      });
      addBatchData2()
      function addBatchData2() {
        const endIndex = Math.min(currentIndex2 + batchSize, mapRes2.length); // 计算本批数据的结束索引
        const newData = mapRes2.slice(currentIndex2, endIndex); // 获取本批数据
        markers2.value = [...markers2.value, ...newData]; // 将本批数据添加到 markers 中
        currentIndex2 += batchSize; // 更新当前数据的索引

        if (currentIndex2 < mapRes2.length) {
          // 如果还有剩余数据，则继续添加下一批数据
          setTimeout(addBatchData2, 200); // 间隔 200ms 添加下一批数据
        } else {
        }
      }
      return mapRes2
    }

    // 视图改变
    const handleRegionChange = (e) => {
      if (isTimer.value) return //loadDing状态 不更新
      if (!e.mpEvent.detail.scale) return //无缩放 不更新
      // console.log(e.mpEvent.detail.scale, e.mpEvent.detail.centerLocation.latitude, 'eeeeeeeeeeee1', mountedNum.value);
      // 用于渲染地图2 确定经纬度
      const mapScale = e.mpEvent.detail.scale; //缩放数
      const myLongitude = e.mpEvent.detail.centerLocation.longitude // 当前经度
      const myLatitude = e.mpEvent.detail.centerLocation.latitude //当前纬度
      let timer = null; // 定义一个变量用来存储定时器
      handleInput() // 监听输入事件，每次输入后都会清除之前的定时器，并重新设置新的定时器
      function handleInput(event) {
        // 每次输入都先清除之前的定时器
        clearTimeout(timer);
        // 重新设置定时器，200ms 后执行逻辑
        timer = setTimeout(() => {
          console.log('myLongitude:', myLongitude);
          // if (!isSelectChange.value) {
            if (myLongitude) {
              longitude2.value = myLongitude
            }
            if (myLatitude) {
              latitude2.value = myLatitude;
            }
          // }
          // 在这里执行你的逻辑，比如发送请求等
        }, 500);
      };

      // 当前缩放大于swatchMapScale 13.1 显示地图2
      if (mapScale >= swatchMapScale.value) {
        if (beforeScale.value < swatchMapScale.value) { // 上一次的缩放 小于swatchMapScale 13.1
          scale.value = e.mpEvent.detail.scale; // 获取当前缩放值 
          if (!map2IsShow.value) { // 是否显示地图2
            loadDingFn(markers.value.length / batchSize * time + 500)
            map2IsShow.value = true // 显示地图2
            isSelectChange.value = true // 通过下拉 显示地图2
            longitude.value = longitude2.value  // 获取地图中心点坐标
            latitude.value = latitude2.value // 获取地图中心点坐标
            changeMapUrl() // 渲染地图2
            // loadDingFn(4000) // 渲染地图2 loadDing
          } else{
            // longitude.value = longitude2.value  // 获取地图中心点坐标
            // latitude.value = latitude2.value // 获取地图中心点坐标
            loadDingFn(600) // 切换地图2 loadDing
            if(selectScale.value != 16){
              longitude.value = longitude2.value  // 获取地图中心点坐标
              latitude.value = latitude2.value // 获取地图中心点坐标 
            }
          }
        }
        beforeScale.value = mapScale // 更新上一次的地图缩放倍数
        // 如果缩放级别小于swatchMapScale 13.1，切换地图1
      } else if (mapScale < swatchMapScale.value) {
        if (beforeScale.value >= swatchMapScale.value) { // 上一次的缩放 小于13.1
          loadDingFn(600) // 切换地图1 loadDing
          scale.value = e.mpEvent.detail.scale; //获取当前缩放值 
        }
        beforeScale.value = mapScale // 更新上一次的地图缩放倍数
      }
    }
    const handleRegionChange2 = (e) => {
      if (isTimer.value) return //loadDing状态 不更新
      // if (mountedNum.value <= 5) return //加载时间小于5 不更新
      if (!e.mpEvent.detail.scale) return //无缩放 不更新
      // console.log(e.mpEvent.detail.scale, 'eeeeeeeeeeee2', mountedNum.value);
      const mapScale = e.mpEvent.detail.scale; //缩放数
      // 当前缩放大于swatchMapScale 13.1 显示地图2
      const myLongitude = e.mpEvent.detail.centerLocation.longitude // 当前经度
      const myLatitude = e.mpEvent.detail.centerLocation.latitude //当前纬度
      let timer = null; // 定义一个变量用来存储定时器
      handleInput() // 监听输入事件，每次输入后都会清除之前的定时器，并重新设置新的定时器
      function handleInput(event) {
        // 每次输入都先清除之前的定时器
        clearTimeout(timer);
        // 重新设置定时器，200ms 后执行逻辑
        timer = setTimeout(() => {
          console.log('myLongitude2:', myLongitude);
            if (myLongitude) {
              longitude2.value = myLongitude
            }
            if (myLatitude) {
              latitude2.value = myLatitude;
            }
          // 在这里执行你的逻辑，比如发送请求等
        }, 500);
      };
      if (mapScale >= swatchMapScale.value) {
        if (beforeScale.value < swatchMapScale.value) { // 上一次的缩放 小于swatchMapScale 13.1
          loadDingFn(600) // 切换地图2 loadDing
          scale.value = e.mpEvent.detail.scale;  // 获取当前缩放值
          if (!map2IsShow.value) { // 是否显示地图2
            map2IsShow.value = true // 显示地图2
          }
        }
        beforeScale.value = mapScale // 更新上一次的地图缩放倍数
      } else if (mapScale < swatchMapScale.value) { // 如果缩放级别小于swatchMapScale 13.1，切换地图1
        if (beforeScale.value >= swatchMapScale.value) { // 上一次的缩放 小于13.1
          loadDingFn(600) // 切换地图1 loadDing
          scale.value = e.mpEvent.detail.scale; //获取当前缩放值
          longitude.value = longitude2.value  // 获取地图中心点坐标
          latitude.value = latitude2.value // 获取地图中心点坐标
          selectScale.value =  e.mpEvent.detail.scale //用于下次判断 是否下拉框放大scale
        }
        beforeScale.value = mapScale // 更新上一次的地图缩放倍数
      }
    }


    // 显示弹出层
    const showPopup = ref(false);
    // 弹出层属性
    const treeObj = reactive({
      memo: "", //备注
      treeList: [],
      treeIndex: 0, //树的索引
      treeSpecTitle: "", //树的规格名称
      planting_tree_specification_amount_min: "", // 最小值
      planting_tree_specification_amount_max: "", // 最大值
      sub_title: "", // 树的索引名称
      planting_tree_id: 2, //种植树种id
      step: 1, // 步骤
      specArr: [], //树的规格数组
      currentSelect: {
        planting_area_name: "", //位置
        planting_area_id: 1, //种植区域id
        planting_tree_name: "", //树的种类名称
        // TreeId: 0, // 树的id
        planting_tree_id: 0, // 树的id
        specTitle: "", //树的规格
        planting_tree_specification_id: "", //树的规格id
        specIndex: 0, // 树的规格索引
        donate_amount: 0, //价格
        number: 1, //数量，
        picture_path: "", //图片
        planting_tree_type: 0, // 种植树类型 0实物 1类型
      },
    });
    // 点击标记点
    const MarkerTap = async (e) => {
      // 初始化
      treeObj.treeIndex = 0; // 选择的树种索引
      treeObj.step = 1; // 第一步
      treeObj.currentSelect.number = 1; //规格数量

      // 获取当前选中地点
      const item = markers.value.filter(
        (item) => item.id == e.detail.markerId
      )[0]; 
      treeObj.currentSelect.planting_area_name = item.name; //地点村名
      treeObj.currentSelect.planting_area_id = item.id; // 树种id

      // 当前区域树种
      // getListTree(e.detail.markerId)
      const ListTreeRes = await ApiListTree(e.detail.markerId);
      treeObj.treeList = ListTreeRes.data;
      // 请求种类对应的规格
      const SpecRes = await ApiListTreeSpecification(
        treeObj.treeList[0].id,
        e.detail.name
      );
      treeObj.specArr = SpecRes.data; // 树种规格
      treeObj.treeSpecTitle = SpecRes.data[0]?.name; // 树种默认规格

      treeObj.sub_title = treeObj.treeList[0]?.name; // 树种名称
      treeObj.planting_tree_specification_amount_min = treeObj.treeList[0]?.planting_tree_specification_amount_min; // 最小值
      treeObj.planting_tree_specification_amount_max = treeObj.treeList[0]?.planting_tree_specification_amount_max; // 最大值
      treeObj.memo = treeObj.treeList[0].memo; // 树种名称
      treeObj.currentSelect.picture_path = treeObj.treeList[0].picture_path; // 树种图片
      treeObj.currentSelect.planting_tree_type = treeObj.treeList[0].type; // 默认种植树类型
      treeObj.currentSelect.planting_tree_id = treeObj.treeList[0]?.id; // 树种id

      showPopup.value = true;

      // 更新下拉框值
      selectedDistrict.value = item.district // 更新下拉镇
      selectedTown.value = item.name // 更新下拉村
      const list = getTownsByDistrict(item.district);
      townsLatitudeList.value = list
      towns.value = list.map((item) => item.name); // 更新所选镇的村列表

      // 请求区域信息
      const p = list.filter(item => item.name == selectedTown.value)[0]
      if (p.id) {
        const res = await ApiStatisticDonateRecordArea(p.id)
        selectedRecordArea.value.area = selectedTown.value
        selectedRecordArea.value.goods = res.data.goods
        selectedRecordArea.value.amount = res.data.amount
        selectedRecordArea.value.amount_sum = res.data.amount_sum
        selectedRecordArea.value.goods_count = res.data.goods_count
        selectedRecordArea.value.amount_count = res.data.amount_count

          // 二次处理数据
        treeObj.treeList.forEach(item => {
          const i = res.data.goods.findIndex(p => p.planting_tree_name == item.name)
          if(i == -1) {
            item.statistic_donate_record_goods_count = 0
          } else {
            item.statistic_donate_record_goods_count = res.data.goods[i].count
          }
          if(res.data.amount_count > 0 && item.name == '助绿金') {
            item.statistic_donate_record_amount_count = res.data.amount_count
          } else if(res.data.amount_count == 0 && item.name == '助绿金'){
            item.statistic_donate_record_amount_count = 0
          }
      })
      }
    };

    // 修改 选中种类标题
    const changeTreeIndex = async (item, i) => {
      treeObj.treeIndex = i; //选中种类索引
      treeObj.currentSelect.planting_tree_id = item.id; // 种植树种id
      treeObj.currentSelect.picture_path = item?.picture_path; // 种植树种图片
      treeObj.sub_title = item.name; // 树种名称
      treeObj.planting_tree_specification_amount_min = item?.planting_tree_specification_amount_min; // 树种规格金额最小值
      treeObj.planting_tree_specification_amount_max = item?.planting_tree_specification_amount_max; // 树种规格金额最大值
      treeObj.memo = item.memo; // 树种描述
      
      treeObj.currentSelect.planting_tree_type = item?.type; // 种植树类型

      // 请求种类对应的规格
      const SpecRes = await ApiListTreeSpecification(item.id);
      treeObj.specArr = SpecRes.data; // 树种规格列表
      treeObj.treeSpecTitle = SpecRes.data[0]?.name; // 树种默认规格
      treeObj.currentSelect.planting_tree_specification_id =
        SpecRes.data[0]?.id; // 种植树种默认规格id
    };

    // 下一步
    const changeStep = async () => {
      // 初始化
      treeObj.currentSelect.specIndex = 0; //默认规格
      treeObj.donate_amount = treeObj.specArr[0]?.donate_amount; // 树种价格
      treeObj.step = 2; //步骤2
      treeObj.currentSelect.planting_tree_name = treeObj.sub_title; //选中的树种名称
    };

    // 确定
    const okStep = async () => {
      // 未选择村
      if (!selectedTown.value) {
        Taro.showToast({
          title: '请先选择村',
          icon: 'none',
          duration: 2000
        })
        return
      }
      Taro.showLoading({
        title: '加载中',
      })
      const list = townsLatitudeList.value.filter((item) => item.name == selectedTown.value); // 所选镇的村列表
      // 请求区域信息
      const p = list.filter(item => item.name == selectedTown.value)[0]
      try {
        if (p.id) {
          // 树种
          const ListTreeRes = await ApiListTree(p.id);
          treeObj.treeList = ListTreeRes.data;
          treeObj.treeList.forEach(item => {
              const i = selectedRecordArea.value.goods.findIndex(p => p.planting_tree_name == item.name)
              if(i == -1) {
                item.statistic_donate_record_goods_count = 0
              } else {
                item.statistic_donate_record_goods_count = selectedRecordArea.value.goods[i].count
              }
              if(selectedRecordArea.value.amount_count > 0 && item.name == '助绿金') {
                item.statistic_donate_record_amount_count = selectedRecordArea.value.amount_count
              } else if(selectedRecordArea.value.amount_count == 0 && item.name == '助绿金'){
                item.statistic_donate_record_amount_count = 0
              }
          })
        }
      } catch (error) {
        Taro.hideLoading()
      }

      // 初始化
      treeObj.treeIndex = 0; //树种索引
      treeObj.step = 1; // 步骤1
      treeObj.currentSelect.number = 1; // 数量
      const item = markers.value.filter(
        (item) => item.name == selectedTown.value
      )[0];// 当前选中村
      treeObj.currentSelect.planting_area_name = item.name; // 村名
      treeObj.currentSelect.planting_area_id = item.id; // 村id
      treeObj.currentSelect.picture_path = treeObj.treeList[0]?.picture_path; // 树种图片
      treeObj.currentSelect.planting_tree_id = treeObj.treeList[0]?.id; // 树种id

      treeObj.planting_tree_specification_amount_min = treeObj.treeList[0]?.planting_tree_specification_amount_min; // 树种规格金额最小值
      treeObj.planting_tree_specification_amount_max = treeObj.treeList[0]?.planting_tree_specification_amount_max;  // 树种规格金额最大值
      treeObj.sub_title = treeObj.treeList[0]?.name; // 树种名称
      treeObj.memo = treeObj.treeList[0]?.memo; // 树种描述

      // 请求种类对应的规格
      try {
        const SpecRes = await ApiListTreeSpecification(
          treeObj.treeList[0].id
        );
        treeObj.specArr = SpecRes.data; // 树种规格
        treeObj.treeSpecTitle = SpecRes.data[0]?.name; // 树种默认规格
        Taro.hideLoading()
      } catch (error) {
        Taro.hideLoading()
      }
      showPopup.value = true; // 显示弹出层
    };

    // 修改规格索引
    const changeSpecIndex = (i) => {
      treeObj.currentSelect.specIndex = i; // 修改规格
      const item = treeObj.specArr[i]
      treeObj.treeSpecTitle = item?.name; // 修改规格名称
      // planting_tree_specification_amount_min
      treeObj.donate_amount = item?.donate_amount; //修改规格金额
    };

    // 确认规格
    const confirmStep2 = () => {
      const currentSelect = treeObj.currentSelect; //对象
      const index = currentSelect.specIndex //规格索引
      console.log(treeObj.specArr, index);

      currentSelect.specTitle =
        treeObj.specArr[index].name; //选中规格名称
      currentSelect.planting_tree_specification_id =
        treeObj.specArr[index].id; // 选中规格id
      currentSelect.donate_amount =
        treeObj.specArr[index].donate_amount; //选中价格

      // 解密
      const returnVal = val => encodeURIComponent(val);
      const returnNumVal = val => encodeURIComponent(Number(val));


      const params = {
        planting_area_name: returnVal(currentSelect.planting_area_name), //区域name 村名
        planting_area_id: returnNumVal(currentSelect.planting_area_id), // 区域id 村id
        picture_path: returnVal(currentSelect.picture_path), // 图片
        // currentSelect: returnVal(currentSelect.currentSelect), // 
        planting_tree_name: returnVal(currentSelect.planting_tree_name), // 树种name 树种名称
        planting_tree_id: returnNumVal(currentSelect.planting_tree_id), // 树种id 树种id
        planting_tree_specification_name: returnVal(currentSelect.specTitle), //规格name 规格名称
        planting_tree_specification_id: returnNumVal( //规格id 
          currentSelect.planting_tree_specification_id
        ),
        memo: returnVal(treeObj.memo), //规格描述
        donate_amount: returnNumVal(currentSelect.donate_amount), // 助绿金额
        donate_number: returnVal(currentSelect.number), // 助绿数量
        planting_tree_type: returnVal(currentSelect.planting_tree_type), // 种植树类型 0实物 1金额
      };
      // console.log(params, "params");

      const queryString = Object.keys(params)
        .map((key) => `${key}=${params[key]}`)
        .join("&");
      Taro.navigateTo({
        url: `/pages/payment/index?${queryString}`,
      });
    };


    // 初始化地图
    onMounted(() => {
      if(infoStore.openid.code != 0) {
        getOpenId();
      }
      getMap(); //请求地图数据
      // getListTree()
    });

    return {
      // 
      // 下拉框
      districts, // 下拉框镇列表
      towns, // 下拉框村列表
      townsLatitudeList, // 村列表总，包括名称
      selectedDistrict, // 当前选择的镇名称
      selectedTown,// 当前选择的村名称
      // 下拉框 更新数据
      onDistrictChange, // 修改选择镇
      onTownChange, // 修改选择村
      onClickTown, //点击村
      // openid
      registerForm, 
      // loadDing定时器
      timer, //定时器
      isTimer,// 时间
      // 显示弹出层
      showPopup,
      // 地图数据 
      areaList, // 请求数据
      markers,// 标记点
      markers2,// 标记点
      latitude, // 纬度
      latitude2,// 纬度
      longitude, // 经度
      longitude2, // 经度
      scale, // 缩放倍数
      selectScale, // 下拉缩放倍数
      beforeScale, // 上次缩放倍数
      MarkerTap, // 点击标记点事件
      // 地图2
      map2IsShow, // 是否显示地图2
      isSelectChange, // 是否通过下拉 显示地图2
      // 缩放地图
      handleRegionChange,
      handleRegionChange2,
      // 图片
      rightImg, 
      icon_dotImg,
      //两个地图倍数临界点
      swatchMapScale,

      // 选择的数据
      treeObj, // 选择数据
      changeStep, // 修改步骤
      changeTreeIndex, // 修改树种索引
      changeSpecIndex, //修改规格索引
      confirmStep2, //确认步骤
      selectedRecordArea,// 镇列表

      // 加载定时器
      mountedNum, // 加载时间数值
      mountedTimer, // 加载定时器
      // 确定
      okStep
    };
  },
};
</script>

<style lang="scss">
.nut-picker {
  background: #ccc;
  // opacity: 0.9;
}

.tree_bottom_box {
  position: fixed;
  bottom: 0;
  z-index: 1000;
  background: #edf2ee;
  // height: 20vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  font-size: 4vw;

  .card {
    background-color: #fff;
    width: 92vw;
    border-radius: 4vw;
    margin: 3vh;
    padding: 2vh 2vw;

    .title {
      font-size: 4.5vw;
    }
  }
}

.tree_info {
  position: fixed;
  bottom: 0;
  z-index: 1000;
  margin-top: 2vh;
  padding-bottom: 2vh;
  background-color: #fff;
  font-size: 4.5vw;
  width: 100vw;
  height: 25vh;
  overflow: auto;

  .title {
    text-align: left;
    font-weight: 600;
    margin-left: 3vw;
    padding-top: 2vh;
    margin-bottom: 2vh;
  }

  .tree_card {
    width: 84vw;
    border-radius: 4vw;
    margin-left: 5vw;
    padding: 2vh 3vw;
    background-color: #f6f6f6;

    .row {
      display: flex;
      align-items: center;
      color: #aaa;
      text-align: left;
      margin-bottom: 1.2vh;

      .span {
        font-weight: 600;
        width: 25vw;
        color: #000;
      }
      .val2 {
        display: flex;
        flex-wrap: wrap;
        flex: 1;
        font-size: 3vw;
        align-items: center;
        .item {
          margin-right: 1vw;
        }
      }

      span {
        flex: 1;
      }

      .val {
        // font-size: 4.8vw;
      }
    }
  }
}

.index {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
}

.top_tip2 {
   border-bottom: 1px solid #ccc;
  .picker_box .right {
    background-color: #fff;
  }

  height: 9vh;
  // opacity: 0.9;
  background-color: hsl(0, 0%, 97%);
  display: flex;
  font-size: 3.6vw;
  align-items: center;
  text-align: left;


  .selectOne {
    margin-right: 2vw;
    margin-left: 2vw;
    width: 40vw;
  }

  .selectTwo {
    width: 40vw;
  }

  .picker {
    padding: 1vh 0;
    display: flex;
    align-items: center;

    .right {
      padding: 1vw 1vw;
      border-radius: 2vw;
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .txt {
        // flex: 1;
        padding-right: 0.5vw;
      }
    }

    .left1 {
      width: 16vw;
      // width: 7vw;
    }

    .left2 {
      width: 16vw;
      // width: 7vw;
    }
  }

  .ok {
    flex: 1;
    text-align: center;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    .btn {
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #4faa71;
      width: 80%;
      height: 50%;
      border-radius: 2vw;
      color: #fff;
    }
  }
}

.top_tip {
  position: fixed;
  top: 0;
  z-index: 999;
  // background-color: #797876;
  // opacity: 0.8;
  color: #fff;
  width: 100vw;
  text-align: center;
  height: 50px;
  line-height: 50px;
  font-size: 4vw;

  .right {
    position: absolute;
    top: 0px;
    right: 2vw;
    font-size: 6vw;
  }
}

.nut_popup_box {
  box-sizing: content-box;
  width: 96vw;
  padding: 3vw 2vw 7vh;
  position: relative;
  height: 74vh;

  // height: 80vh;
  // background-color: #cfc;
  .top_title {
    font-weight: 600;
    margin-bottom: 2vh;
  }

  .tree_box {
    .top {
      display: flex;

      .left_box {
        .img {
          width: 33vw;
          height: 37vw;
          // background-image: url("http://tree-planting.dgsxczxcjh.org.cn/image/JwcWcuL83EQCBtv2Zhb7Lc6ED76rlN6og48W5uaX.png");
          background-size: cover;
          /* 确保图片覆盖整个容器 */
        }
      }

      .right_box {
        margin-left: 2vw;
        text-align: left;
        font-size: 3.7vw;

        .title {
          margin-bottom: 0.7vh;
          display: flex;
          align-items: center;
        }

        .small_tree {
          font-size: 3vw;
          color: #aaa;
        }

        .mid_title {
          margin-bottom: 0.7vh;
        }

        .mid_title2 {
          font-size: 3.3vw;
          margin-bottom: 0.6vh;
        }

        .small_title {
          color: #aaa;
        }
      }
    }

    .select {
      padding-bottom: 13vh;
      .type {
        text-align: left;
        font-weight: 600;
        margin-top: 2vh;
        margin-bottom: 2vh;
      }

      .treeList {
        display: flex;
        flex-wrap: wrap;
        width: 96vw;
        overflow: auto;

        .active {
          color: #1eb482;
          background-color: #f3faf8;
        }

        .txt_box {
          margin-bottom: 2vh;
          width: 31%;
          background-color: #f3f3f3;
          font-size: 4vw;
          white-space: nowrap;
          color: #000;
          text-align: center;

          .box {
            overflow: auto;
            width: 88%;
            padding: 1vh 2vw;

            .small_tree {
              font-size: 3vw;
              color: #aaa;
            }
          }
        }
      }

      .tree_button {
        // position: absolute;
        // bottom: 3vh;
        // display: flex;
        // justify-content: center;
        // width: 96vw;

        position: fixed;
        background-color: #fff;
        z-index: 9999;
        bottom: 0vh;
        width: 96vw;
        padding-bottom: 3vh;

        button {
          background-color: #1eb482;
          color: #fff;
          border-radius: 8vw;
          border: none;
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }

      .margin_right {
        margin-right: 2vw;
      }

      .number {
        height: 3vh;
        display: flex;
        justify-content: space-between;
        margin-top: 2vh;
        margin-bottom: 2vh;

        .step2Number {
          font-weight: 600;
        }

        .btn_box {
          display: flex;
          align-items: center;
          line-height: 60px;

          button {
            width: 60px;
            height: 60px;
            display: flex;
            justify-content: center;
            line-height: 60px;
            color: #555;
          }

          .num {
            background-color: #f2f3f5;
            color: #555;
            display: inline-block;
            width: 60px;
            height: 60px;
            margin: 0 1vw;
          }
        }
      }

      .spec {
        display: flex;
        flex-wrap: wrap;
        width: 96vw;
        padding-bottom: 20vh;

        .active {
          color: #1eb482;
          background-color: #f3faf8;
        }

        .txt_box {
          margin-bottom: 2vh;
          width: 100%;
          background-color: #f3f3f3;
          font-size: 4vw;
          white-space: nowrap;
          color: #000;
          text-align: center;

          .box {
            overflow: auto;
            width: 94%;
            padding: 1vh 2vw;
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;

            .money {
              position: absolute;
              right: 4vw;
            }
          }
        }
      }

      .tree_button_step2 {
        // height: 6vh;
        position: fixed;
        background-color: #fff;
        z-index: 9999;
        bottom: 0vh;
        width: 96vw;
        padding-bottom: 3vh;

        .Back {
          margin: 2.5vh 0;
          color: #1eb482;
        }

        button {
          background-color: #1eb482;
          color: #fff;
          border-radius: 8vw;
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }
}
</style>
